package com.lichuang.dedao.listenBooks.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lichuang.dedao.listenBooks.entity.Category;
import com.lichuang.dedao.listenBooks.entity.ListenBooks;
import com.lichuang.dedao.listenBooks.mapper.ListenBooksMapper;
import com.lichuang.dedao.listenBooks.service.ICategoryService;
import com.lichuang.dedao.listenBooks.service.IListenBooksService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 听书 服务实现类
 * </p>
 *
 * @author kangkang
 * @since 2019-07-12
 */
@Service
public class ListenBooksServiceImpl extends ServiceImpl<ListenBooksMapper, ListenBooks> implements IListenBooksService {

    @Autowired
    private ICategoryService categoryService;

    @Override
    public List<ListenBooks> selectLisenBooks() {
        return baseMapper.selectList(new QueryWrapper<>());
    }

    @Override
    public List<ListenBooks> selectLisenBooksByCategory(Integer categoryId) {
        // 如果分类id的pid是-1，就查询所有二级分类的所有书
        Category category = categoryService.selectCategoryById(categoryId);
        Integer pid = category.getPid();
        ListenBooks listenBooksParam = new ListenBooks();
        QueryWrapper queryWrapper = new QueryWrapper();
        // 表示一级分类
        if (pid == -1) {
            // 子分类的集合
            List<Category> categories = categoryService.selectCategoriesByPid(categoryId);
            List<ListenBooks> listenBooksList = new LinkedList<>();
            for (Category category1 : categories) {
                listenBooksParam.setCategoryId(category1.getId());
                queryWrapper.setEntity(listenBooksParam);
                List<ListenBooks> listenBooks = baseMapper.selectList(queryWrapper);
                listenBooksList.addAll(listenBooks);
            }
            return listenBooksList;
        }
        listenBooksParam.setCategoryId(categoryId);
        queryWrapper.setEntity(listenBooksParam);
        List<ListenBooks> listenBooks = baseMapper.selectList(queryWrapper);
        return listenBooks;
    }
}
